<template>
  <div id="app">
    <!-- Nav组件 -->
    <!-- //$route.meta.sindetail 跳转后隐藏菜单栏 -->
    <top-nav v-show="!$route.meta.sindetail">菜单栏</top-nav>
    <!-- v-if="currentMusic" 因为null是对象,ajax是异步的,直接取值会报错 得加判断v-if-->
    <play v-if="currentMusic" 
    :currentMusic="currentMusic"
    :playList="playList"
    @changeMusic="changeMusic"
    ></play >
    <!-- exclude="playList" 任何名称匹配的组件都不会被缓存 -->
    <!-- keep-alive 组件缓存 -->
    <!-- <keep-alive exclude="Search">   -->
      <router-view @play="play"/>
    <!-- </keep-alive> -->
  </div>
</template>
<script>
import TopNav from '@/components/TopNav.vue';
import Play from '@/components/Play.vue';

export default {
  data(){
    return {
      currentMusic:null,   //null是对象;ajax是异步的,如果直接取值会报错,所以得加判断v-if
      playList:[], //当前播放歌单
    }
  },
  methods:{
    play(event){  //播放事件  event是对象(MsicList.vue遍历的 song 对象)
      // console.log("event==>",event)
      if(event.al && event.al.picUrl){
        event.picUrl=event.al.picUrl;
      }
      // 把当前播放音乐赋值给currentMusic
      this.currentMusic=event;
      // 加入歌单的时候需要去重
      let isRepeat=false; //记录是否有重复
      this.playList.forEach((v)=>{
        if(v.id==event.id){
          isRepeat=true;
        }
      });
      if(!isRepeat){
        this.playList.push(event); //把当前 播放音乐 存入歌单
      }
    },
    // 点击切换音乐
    /**data数据 currentMusic对象装的是当前播放的音乐,换音乐 只需改变 currentMusic  */
    changeMusic(event){
      let currIndex=0;
      this.playList.forEach((v,index)=>{
        // 如果歌单里的音乐id与当前点击的音乐id一致,就高亮它
        if(v.id==this.currentMusic.id){
          currIndex=index;  //查找当前播放音乐在歌单数组里面的下标
        }
      })
      if(event=='prev'){
        if(currIndex==0){//判断上一曲的当前下标为0,去掉最后一曲,
          currIndex=this.playList.length-1;
        }
        else{
          currIndex--;
        }

      }else if(event=='next'){
        if(currIndex==this.playList.length-1){
          currIndex=0;
        }else{
          currIndex++;
        }
      } else if(typeof event== 'object'){
        this.currentMusic=event;
        return;
      }
      this.currentMusic=this.playList[currIndex];
      // console.log(event,this.currentMusic.id);
    },
  },
  created(){
  },
  components:{
    'top-nav':TopNav,
    Play
    
  }
    
}
</script>
<style lang="less" scoped>
</style>
